package com.template.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fqj.fqjcommon.model.entity.InterfaceInfo;
import com.fqj.fqjcommon.model.entity.UserInterfaceInfo;
import com.template.project.annotation.AuthCheck;
import com.template.project.common.BaseResponse;
import com.template.project.common.ErrorCode;
import com.template.project.common.ResultUtils;
import com.template.project.exception.BusinessException;
import com.template.project.mapper.UserInterfaceInfoMapper;
import com.template.project.model.vo.InterfaceInfoVo;
import com.template.project.service.InterfaceInfoService;
import jdk.nashorn.internal.ir.CallNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分析控制器
 */
@RestController
@RequestMapping("/analysis")
@Slf4j
public class AnalysisController {

	@Resource
	private UserInterfaceInfoMapper userInterfaceInfoMapper;
	@Resource
	private InterfaceInfoService interfaceInfoService;

	@GetMapping("/top/interface/invoke")
	@AuthCheck(mustRole = "admin")
	public BaseResponse<List<InterfaceInfoVo>> listTopInvokeInterfaceInfo(){
		List<UserInterfaceInfo> userInterfaceInfos = userInterfaceInfoMapper.listTopInvokeInterfaceInfo(3);
		Map<Long, List<UserInterfaceInfo>> InterfaceInfoObjMap = userInterfaceInfos.stream().
				collect(Collectors.groupingBy(UserInterfaceInfo::getInterfaceInfoId));
		QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("id",InterfaceInfoObjMap.keySet());
		List<InterfaceInfo> list = interfaceInfoService.list(queryWrapper);
		if (CollectionUtils.isEmpty(list)){
			throw new BusinessException(ErrorCode.SYSTEM_ERROR);
		}
		List<InterfaceInfoVo> interfaceInfoVOList = list.stream().map(interfaceInfo -> {
			InterfaceInfoVo interfaceInfoVo = new InterfaceInfoVo();
			BeanUtils.copyProperties(interfaceInfo, interfaceInfoVo);
			int totalNum = InterfaceInfoObjMap.get(interfaceInfo.getId()).get(0).getTotalNum();
			interfaceInfoVo.setTotalNum(totalNum);
			return interfaceInfoVo;
		}).collect(Collectors.toList());
		return ResultUtils.success(interfaceInfoVOList);
	}
}
